import { Picker, View } from '@tarojs/components'
import { useMemo } from 'react'
import { Arrow } from '@taroify/icons'
import { formContextProvider } from '../BtForm/formContextProvider';
import Validator from '../BtForm/validator';
import './index.scss'

interface BtPickerProps {
  name?: string
  value: string
  rangeKey?: string
  rangeVal?: string
  selector: any[]
  prop?: string
  onChange: (value) => void
}

export default function BtPicker ( {value, onChange, selector, rangeKey = 'name', rangeVal = 'id', prop=''}: BtPickerProps) {
   const [state] = formContextProvider.useTracked()

  const validFormItem = async (inputValue) => {
    const rule = {}
    const field = state.fields.find(item => item.prop === prop)
    if (!field) return
    if (state.rules[prop]) {
      rule[prop] = state.rules[prop]
    }
    const validator = new Validator(rule)
    const errs = await validator.validate({ [prop]: inputValue })
    const msg = (errs && errs[0].message) || ''
    field.setErrMsg(msg)
  }

  const computeText = val => {
    const item = selector.find(i => i[rangeVal] === val)
    return item ? item.name : '请选择'
  }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const text = useMemo(() => {return computeText(value)}, [ value ])

  const textClass = `content ${text === '请选择' ? 'placeholder' : ''}`;

  const handleOnChange = (e) => {
    const inputValue = selector[e.detail.value][rangeVal]
    validFormItem(inputValue)
    onChange({detail: {value: inputValue}})
  }

  return (
    <Picker mode='selector' range={selector}
      onChange={(e) => { handleOnChange(e) }}
      rangeKey={rangeKey}
    >
      <View className='picker-content flex justify-between items-center'>
        <View className={textClass}>{text}</View>
        <Arrow color='#333' />
      </View>
    </Picker>
  )
}
